<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.groups.createGroup')"
    width="400px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item :label="$t('contacts.groups.groupName')" prop="groupName">
        <el-input
          v-model="form.groupName"
          :placeholder="$t('contacts.groups.groupNamePlaceholder')"
          maxlength="20"
          show-word-limit
          @keydown.enter="handleSubmit"
        />
      </el-form-item>
      
      <el-form-item :label="$t('contacts.groups.groupDescription')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :placeholder="$t('contacts.groups.groupDescriptionPlaceholder')"
          maxlength="100"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
        >
          {{ $t('contacts.groups.createGroup') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useContactsStore } from '@/stores/contacts'
import { contactsApi } from '@/api/contacts'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'created': [groupName: string]
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  groupName: '',
  description: ''
})

// 表单验证规则
const rules: FormRules = {
  groupName: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分组名称长度在 1 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 检查分组名称是否已存在
        if (contactsStore.friendGroups.includes(value)) {
          callback(new Error('分组名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  description: [
    { max: 100, message: '描述不能超过100个字符', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听对话框显示状态
watch(visible, (newVisible) => {
  if (newVisible) {
    resetForm()
  }
})

// 方法
const resetForm = () => {
  form.groupName = ''
  form.description = ''
  formRef.value?.clearValidate()
}

const handleClose = () => {
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 验证表单
    await formRef.value.validate()
    
    loading.value = true

    // 创建分组（这里暂时只是模拟，实际需要调用API）
    await createGroup()
    
    ElMessage.success('分组创建成功')
    emit('created', form.groupName)
    visible.value = false

  } catch (error: any) {
    console.error('创建分组失败:', error)
    if (error !== false) { // 不是表单验证失败
      const errorMessage = error.message || error.response?.data?.message || '创建分组失败，请重试'
      ElMessage.error(errorMessage)
    }
  } finally {
    loading.value = false
  }
}

const createGroup = async () => {
  try {
    // 调用后端API创建分组
    const response = await contactsApi.createFriendGroup({
      groupName: form.groupName,
      description: form.description,
      sortOrder: 0
    })

    console.log('API响应:', response)

    // 创建成功，通过emit通知父组件刷新
    return true
  } catch (error: any) {
    console.error('API调用失败:', error)
    throw new Error(error.response?.data?.message || error.message || '创建分组失败')
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>
